/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 *
 * Function : z = x + y
 * This sample is a very basic sample that implements vector add on Ascend plaform.
 */
#include "kernel_operator.h"
// tensor num for each queue
constexpr int32_t BUFFER_NUM = 2;

template<typename TYPE_X, typename TYPE_Y, typename TYPE_Z> class KernelAdd {
    using T = TYPE_X;
public:
    __aicore__ inline KernelAdd() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, uint32_t smallCoreDataNum,
                                uint32_t bigCoreDataNum, uint32_t finalBigTileNum, 
                                uint32_t finalSmallTileNum, uint32_t tileDataNum, 
                                uint32_t smallTailDataNum, uint32_t bigTailDataNum, 
                                uint32_t tailBlockNum, float rtol, float atol) 
    {
        this->rtol = rtol;
        this->atol = atol;
        ASSERT(AscendC::GetBlockNum() != 0 && "block dim can not be zero!");
        uint32_t coreNum = AscendC::GetBlockIdx();
        uint32_t globalBufferIndex = bigCoreDataNum * AscendC::GetBlockIdx();
        this->tileDataNum = tileDataNum;
        if (coreNum < tailBlockNum) { 
          this->coreDataNum = bigCoreDataNum;
          this->tileNum = finalBigTileNum;
          this->tailDataNum = bigTailDataNum;
        }
        else { 
          this->coreDataNum = smallCoreDataNum;
          this->tileNum = finalSmallTileNum;
          this->tailDataNum = smallTailDataNum;
          globalBufferIndex -= (bigCoreDataNum - smallCoreDataNum) * (AscendC::GetBlockIdx() - tailBlockNum);
        }

        AscendC::printf("info:%d %d %d %d\n", this->tileDataNum, this->coreDataNum, this->tileNum, this->tailDataNum);
        xGm.SetGlobalBuffer((__gm__ TYPE_X*)x + globalBufferIndex, this->coreDataNum);
        yGm.SetGlobalBuffer((__gm__ TYPE_Y*)y + globalBufferIndex, this->coreDataNum);
        zGm.SetGlobalBuffer((__gm__ TYPE_Z*)z + globalBufferIndex, this->coreDataNum);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileDataNum * sizeof(TYPE_X));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->tileDataNum * sizeof(TYPE_Y));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileDataNum * sizeof(TYPE_Z));
        pipe.InitBuffer(cmp, this->tileDataNum * sizeof(uint8_t));
        pipe.InitBuffer(tmp1, this->tileDataNum * sizeof(float));
        pipe.InitBuffer(tmp2, this->tileDataNum * sizeof(float));
        pipe.InitBuffer(tmp3, this->tileDataNum * sizeof(float));
        pipe.InitBuffer(tmp4, this->tileDataNum * sizeof(float));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum;
        this->processDataNum = this->tileDataNum;
        for (int32_t i = 0; i < loopCount; i++) {
            if (i == this->tileNum - 1) {
              this->processDataNum = this->tailDataNum;
            }
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.AllocTensor<TYPE_X>();
      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.AllocTensor<TYPE_Y>();
      AscendC::DataCopy(xLocal, xGm[progress * this->tileDataNum], this->processDataNum);
      AscendC::DataCopy(yLocal, yGm[progress * this->tileDataNum], this->processDataNum);
      inQueueX.EnQue(xLocal);
      inQueueY.EnQue(yLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_X> xLocal = inQueueX.DeQue<TYPE_X>();
      AscendC::LocalTensor<TYPE_Y> yLocal = inQueueY.DeQue<TYPE_Y>();
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.AllocTensor<TYPE_Z>();
      auto p1 = tmp1.Get<half>();
      auto p2 = tmp2.Get<half>();
      auto cmp_result = cmp.Get<uint8_t>();
      AscendC::Duplicate(p1, half(0),  this->processDataNum);
      // AscendC::Duplicate(p2, half(1),  this->processDataNum);

      if constexpr (std::is_same_v<T, int32_t>) {
        auto p3 = tmp3.Get<float>();
        auto p4 = tmp4.Get<float>();

        AscendC::Cast(p3, xLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);
        AscendC::Cast(p4, yLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);
        float rtol = this->rtol;
        float atol = this->atol;
        // AscendC::Compare(cmp_result, p3, p4, AscendC::CMPMODE::EQ, this->processDataNum);


        AscendC::Sub(p3, p3, p4, this->processDataNum);
        AscendC::Abs(p3, p3, this->processDataNum);
        AscendC::Abs(p4, p4, this->processDataNum);
        AscendC::Muls(p4, p4, rtol, this->processDataNum);
        AscendC::Adds(p4, p4, atol, this->processDataNum);
        AscendC::Compare(cmp_result, p3, p4, AscendC::CMPMODE::GT, this->processDataNum);

      }

      else if constexpr (std::is_same_v<T, uint8_t>) {
        auto p3 = tmp3.Get<half>();
        auto p4 = tmp4.Get<half>();
        half rtol = half(this->rtol);
        half atol = half(this->atol);
        AscendC::Cast(p3, xLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);
        AscendC::Cast(p4, yLocal, AscendC::RoundMode::CAST_NONE, this->processDataNum);
        // AscendC::Compare(cmp_result, p3, p4, AscendC::CMPMODE::EQ, this->processDataNum);
        
        AscendC::Sub(p3, p3, p4, this->processDataNum);
        AscendC::Abs(p3, p3, this->processDataNum);
        AscendC::Abs(p4, p4, this->processDataNum);
        AscendC::Muls(p4, p4, rtol, this->processDataNum);
        AscendC::Adds(p4, p4, atol, this->processDataNum);
        AscendC::Compare(cmp_result, p3, p4, AscendC::CMPMODE::GT, this->processDataNum);

      }
      else {
        T rtol = T(this->rtol);
        T atol = T(this->atol);
        AscendC::Sub(xLocal, xLocal, yLocal, this->processDataNum);
        AscendC::Abs(xLocal, xLocal, this->processDataNum);
        AscendC::Abs(yLocal, yLocal, this->processDataNum);
        AscendC::Muls(yLocal, yLocal, rtol, this->processDataNum);
        AscendC::Adds(yLocal, yLocal, atol, this->processDataNum);
        AscendC::Compare(cmp_result, xLocal, yLocal, AscendC::CMPMODE::GT, this->processDataNum);
        // AscendC::Compare(cmp_result, xLocal, yLocal, AscendC::CMPMODE::EQ, this->processDataNum);

      }
      AscendC::Select(p2, cmp_result, p1, half(1), AscendC::SELMODE::VSEL_TENSOR_SCALAR_MODE, this->processDataNum);
      AscendC::Cast(zLocal, p2, AscendC::RoundMode::CAST_NONE, this->processDataNum);
      outQueueZ.EnQue<TYPE_Z>(zLocal);
      inQueueX.FreeTensor(xLocal);
      inQueueY.FreeTensor(yLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
      AscendC::LocalTensor<TYPE_Z> zLocal = outQueueZ.DeQue<TYPE_Z>();  
      AscendC::DataCopy(zGm[progress * this->tileDataNum], zLocal, this->processDataNum);
      outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::QuePosition::VECIN, BUFFER_NUM> inQueueX, inQueueY;
    AscendC::TQue<AscendC::QuePosition::VECOUT, BUFFER_NUM> outQueueZ;

    AscendC::TBuf<AscendC::QuePosition::VECCALC> cmp, tmp1, tmp2, tmp3, tmp4;
    AscendC::GlobalTensor<TYPE_X> xGm;
    AscendC::GlobalTensor<TYPE_Y> yGm;
    AscendC::GlobalTensor<TYPE_Z> zGm;
    uint32_t coreDataNum;
    uint32_t tileNum;
    uint32_t tileDataNum;
    uint32_t tailDataNum;
    uint32_t processDataNum;
    float rtol, atol;
};

extern "C" __global__ __aicore__ void is_close(GM_ADDR x, GM_ADDR y, GM_ADDR z, GM_ADDR workspace, GM_ADDR tiling)
{
    GET_TILING_DATA(tiling_data, tiling);
    KernelAdd<DTYPE_X1, DTYPE_X1, uint8_t> op;
    op.Init(x, y, z, tiling_data.smallCoreDataNum, 
            tiling_data.bigCoreDataNum, tiling_data.finalBigTileNum, 
            tiling_data.finalSmallTileNum, tiling_data.tileDataNum, 
            tiling_data.smallTailDataNum, tiling_data.bigTailDataNum, 
            tiling_data.tailBlockNum, tiling_data.rtol, tiling_data.atol);  
    op.Process();
}

